package cn.lj.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * @file: SecurityConfig
 * @version: 1.0
 * @Description: Security配置类
 * @author: 李津
 * @date: 2021-05-21 15:18
 * 本代码要注意的事项、备注事项等
 */

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //不拦截的白名单
    private static final String[] URL_WHITELIST = {
            "/login", "/logout", "/captcha", "/favicon.ico",
            "/css/**",
            "/js/**",
            "/images/**",
            "/doc.html", "/swagger-ui.html",
    };

    private final LoginFailureHandler loginFailureHandler;
    private final LoginSuccessHandler loginSuccessHandler;
    private final CaptchaFilter captchaFilter;
    private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
    private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private final UserDetailServiceImpl userDetailService;
    private final JwtLogoutSuccessHandler jwtLogoutSuccessHandler;

    @Autowired
    public SecurityConfig(LoginFailureHandler loginFailureHandler, LoginSuccessHandler loginSuccessHandler, CaptchaFilter captchaFilter, JwtAccessDeniedHandler jwtAccessDeniedHandler, JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, UserDetailServiceImpl userDetailService, JwtLogoutSuccessHandler jwtLogoutSuccessHandler) {
        this.loginFailureHandler = loginFailureHandler;
        this.loginSuccessHandler = loginSuccessHandler;
        this.captchaFilter = captchaFilter;
        this.jwtAccessDeniedHandler = jwtAccessDeniedHandler;
        this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
        this.userDetailService = userDetailService;
        this.jwtLogoutSuccessHandler = jwtLogoutSuccessHandler;
    }

    /**
     * 认证过滤器
     * @return
     * @throws Exception
     */
    @Bean
    JWTAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JWTAuthenticationFilter(authenticationManager());
    }

    /**
     * 密码加密
     * @return
     */
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * SecurityConfig
     *
     * @param http
     * @throws Exception
     */
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().and().csrf().disable()

                //开发阶段接口测试\开放swagger
                .authorizeRequests()
                .antMatchers(
                        "/v2/api-docs",//swagger api json
                        "/swagger-resources",//用来获取api-docs的URI
                        "/swagger-resources/**",//用来获取支持的动作//安全选项
                        "/configuration/ui",
                        "/configuration/security",
                        "/swagger-ui.html/**",
                        "/webjars/**"
                ).permitAll()

                .and()
                // 登录配置
                .formLogin()
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)

                // 退出配置
                .and()
                .logout()
                .logoutSuccessHandler(jwtLogoutSuccessHandler)

                // 禁用session//基于token，不需要session
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                // 配置拦截规则
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated()

                // 异常处理器
                .and()
                .exceptionHandling()
                //定义认证失败处理类
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                //访问拒绝处理
                .accessDeniedHandler(jwtAccessDeniedHandler)

                // 配置自定义的过滤器
                .and()
                //认证过滤器
                .addFilter(jwtAuthenticationFilter())
                //验证码验证在用户验证之前
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
        ;

    }


    /**
     * userDetailService
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);
    }
}
